# -*- codeing = utf-8 -*-
# @Time: 2021/12/15 19:42
# @Author: Foxhuty
# @File: invigilation_test.py
# @Software: PyCharm
# @Based on python 3.9

import pandas as pd
import numpy as np
import random
import time

filepath = r'D:\work documents\高2021级\高一监考数据.xlsx'
df = pd.read_excel(filepath, index_col='id', sheet_name='teacher_names', dtype={'id': str})
exam_numbers = 6
room_numbers = 9

df_teachers = df[df['leader'] != 'yes']
df_teachers = df_teachers.loc[:, 'name']
df_care = df.loc[df['care'] == 'yes', 'name']
care_list = df_care.values.tolist()


def invigilation_table():
    teacher_list = df_teachers.values
    # random.seed(10)
    random.shuffle(teacher_list)
    exam_room = pd.DataFrame(columns=['Exam' + str(i + 1) for i in range(exam_numbers)],

                             index=['Room' + str(i + 1) for i in range(room_numbers)])
    exam_room.index.rename('room_numbers', inplace=True)
    exam_room.reset_index(inplace=True)
    nums = 0
    try:
        for i in exam_room.columns[1:]:
            for k in exam_room.index:
                exam_room[i].at[k] = teacher_list[nums]
                # 确保数据连续选取
                if nums < len(teacher_list) - 1:
                    nums += 1
                else:
                    nums = 0
    except KeyError:
        exam_room.fillna(np.NaN)
    exam_room.set_index('room_numbers', inplace=True)

    return exam_room


def use_time(f):
    def wrapper(*args, **kwargs):
        t1 = time.time()
        results = f(*args, **kwargs)
        t2 = time.time()
        print(f'主程序{f.__name__}用时{(t2 - t1):.1f}秒')
        return results

    return wrapper


@use_time
def final_table():
    df_room = invigilation_table()
    rooms = df_room.index
    df_list_bottom_2 = df_room.loc[rooms[-2]].values.tolist()
    df_list_bottom_1 = df_room.loc[rooms[-1]].values.tolist()
    bottom_2 = list(set(df_list_bottom_2).union(set(df_list_bottom_1)))
    n = 0
    while list(set(care_list).intersection(set(bottom_2))):
        df_room = invigilation_table()
        df_list_bottom_2 = df_room.loc[rooms[-2]].values.tolist()
        df_list_bottom_1 = df_room.loc[rooms[-1]].values.tolist()
        bottom_2 = list(set(df_list_bottom_2).union(set(df_list_bottom_1)))
        n += 1
        print(df_room)
        print(f'共计运行{n}次')


def dupe_list(lst):
    set_lst = set(lst)
    if len(set_lst) == len(lst):
        return False
    else:
        return True


def care_table():
    df_room = invigilation_table()
    # print(df_room)
    num = 0
    for i in df_room.columns:
        for k in df_room.index[-2:]:
            for j in df_room.columns[num:]:
                for h in df_room.index[0:-2]:
                    if (df_room[i].at[k] in care_list) and (df_room[j].at[h] not in care_list):
                        df_room[i].at[k], df_room[j].at[h] = df_room[j].at[h], df_room[i].at[k]
                        # print(df_room)
                        num += 1
    # print(df_room)
    return df_room


# care_df = care_table()
# for i in care_df.columns:
#     dupes = care_df[i].values.tolist()
#     flag = dupe_list(dupes)
#     if flag:
#         print(dupes)

care = care_table()
print(care)
# writer = pd.ExcelWriter(r'D:\成绩统计结果\监考安排信息表.xlsx')
# print(care_list)
# print(df_room)
# df_room.to_excel(writer, sheet_name='invigilation_table')
# teachers = df_room.values
# teacher_dict = {}
# for i in range(len(teachers)):
#     for k in teachers[i]:
#         teacher_dict[k] = teacher_dict.get(k, 0) + 1
# teacher_occupied = list(teacher_dict.items())
# teacher_occupied.sort(key=lambda x: x[1], reverse=True)
# invigilators = []
# invigilation_times = []
# for i in range(len(teacher_occupied)):
#     teacher, times = teacher_occupied[i]
#     invigilators.append(teacher)
#     invigilation_times.append(times)
#     print('{0:>6}老师：    监考{1:<}节'.format(teacher, times))
# print(f'共有{len(teacher_occupied)}个老师参与本次监考')
# invigilation_df = pd.DataFrame({'id': [i + 1 for i in range(len(invigilators))], 'teacher_names': invigilators,
#                                 'invigilation_times': invigilation_times})
# invigilation_df.set_index('id', inplace=True)
# invigilation_df.loc['total'] = [invigilation_df['teacher_names'].count(),
#                                 invigilation_df['invigilation_times'].sum()]
# invigilation_df.to_excel(writer, sheet_name='invigilation_staff')
# writer.close()
